<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon sales">
              <el-icon size="24"><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥1,234,567</div>
              <div class="stat-label">今日销售额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon orders">
              <el-icon size="24"><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">156</div>
              <div class="stat-label">今日订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon inventory">
              <el-icon size="24"><Box /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">2,345</div>
              <div class="stat-label">库存商品</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon customers">
              <el-icon size="24"><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">89</div>
              <div class="stat-label">新增客户</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 业务统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6" :lg="4">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon purchase">
              <el-icon size="24"><ShoppingCart /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ purchaseStats.count }}</div>
              <div class="stat-label">采购订单数</div>
              <div class="stat-sub">金额: ¥{{ purchaseStats.amount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6" :lg="4">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon distribution">
              <el-icon size="24"><Van /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ distributionStats.count }}</div>
              <div class="stat-label">配货任务数</div>
              <div class="stat-sub">待处理: {{ distributionStats.pending }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6" :lg="4">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon wholesale">
              <el-icon size="24"><Sell /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ wholesaleStats.count }}</div>
              <div class="stat-label">批发订单数</div>
              <div class="stat-sub">金额: ¥{{ wholesaleStats.amount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6" :lg="4">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon transfer">
              <el-icon size="24"><Connection /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ transferStats.count }}</div>
              <div class="stat-label">移仓单数</div>
              <div class="stat-sub">件数: {{ transferStats.items }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6" :lg="4">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon dataflow">
              <el-icon size="24"><DataAnalysis /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ dataFlowStats.total }}</div>
              <div class="stat-label">数据流转量</div>
              <div class="stat-sub">增长率: {{ dataFlowStats.growth }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6" :lg="4">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon integration">
              <el-icon size="24"><Link /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ integrationStats.apis }}</div>
              <div class="stat-label">API调用次数</div>
              <div class="stat-sub">成功率: {{ integrationStats.successRate }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 业务数据图表 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>业务数据对比</span>
              <el-button size="small" type="primary" plain @click="refreshBusinessStats">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <div class="chart-container">
            <v-chart 
              :option="businessCompareChartOption" 
              style="height: 300px; width: 100%;"
              autoresize
            />
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>业务数据分布</span>
              <el-button size="small" type="primary" plain @click="refreshBusinessStats">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <div class="chart-container">
            <v-chart 
              :option="businessDistributionChartOption" 
              style="height: 300px; width: 100%;"
              autoresize
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :lg="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>销售趋势</span>
              <el-button-group>
                <el-button size="small" :type="chartPeriod === '7d' ? 'primary' : ''" @click="chartPeriod = '7d'">7天</el-button>
                <el-button size="small" :type="chartPeriod === '30d' ? 'primary' : ''" @click="chartPeriod = '30d'">30天</el-button>
                <el-button size="small" :type="chartPeriod === '90d' ? 'primary' : ''" @click="chartPeriod = '90d'">90天</el-button>
              </el-button-group>
            </div>
          </template>
          <div class="chart-container">
            <v-chart 
              :option="salesChartOption" 
              style="height: 300px; width: 100%;"
              autoresize
            />
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>登录时间段统计</span>
              <el-button size="small" type="primary" plain @click="refreshLoginTimeData">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <div class="chart-container" v-loading="loginTimeDataLoading">
            <v-chart 
              :option="loginTimeChartOption" 
              style="height: 300px; width: 100%;"
              autoresize
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 业务数据流转图 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>业务数据流转全景图</span>
              <el-button size="small" type="primary" plain @click="refreshDataFlow">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <div class="chart-container">
            <v-chart 
              :option="dataFlowSankeyOption" 
              style="height: 500px; width: 100%;"
              autoresize
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 登录统计 -->
    <el-row :gutter="20" class="login-stats-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>最近30天登录次数统计</span>
              <div class="header-actions">
                <!-- 图表类型切换 -->
                <el-radio-group v-model="loginChartType" size="small">
                  <el-radio-button value="bar">
                    <el-icon><DataLine /></el-icon>
                    柱状图
                  </el-radio-button>
                  <el-radio-button value="line">
                    <el-icon><TrendCharts /></el-icon>
                    折线图
                  </el-radio-button>
                  <el-radio-button value="area">
                    <el-icon><DataAnalysis /></el-icon>
                    面积图
                  </el-radio-button>
                  <el-radio-button value="smooth">
                    <el-icon><Promotion /></el-icon>
                    平滑曲线
                  </el-radio-button>
                </el-radio-group>
                <el-button size="small" type="primary" plain @click="refreshLoginData">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </div>
          </template>
          <div class="chart-container" v-loading="loginDataLoading">
            <v-chart 
              :option="loginChartOption" 
              style="height: 350px; width: 100%;"
              autoresize
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快捷操作和最近活动 -->
    <el-row :gutter="20" class="bottom-row">
      <el-col :xs="24" :lg="12">
        <el-card class="action-card">
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
              <div class="header-actions">
                <el-button size="small" type="primary" @click="showAddShortcutDialog">
                  <el-icon><Plus /></el-icon>
                  添加快捷方式
                </el-button>
                <el-button size="small" type="default" @click="showManageShortcutsDialog">
                  <el-icon><Setting /></el-icon>
                  管理
                </el-button>
              </div>
            </div>
          </template>
          <div class="quick-actions">
            <el-button 
              v-for="shortcut in shortcuts" 
              :key="shortcut.id"
              :type="shortcut.type"
              @click="handleShortcutClick(shortcut)"
            >
              <el-icon><component :is="shortcut.icon" /></el-icon>
              {{ shortcut.name }}
            </el-button>
            
            <!-- 如果没有快捷操作，显示提示 -->
            <el-empty 
              v-if="shortcuts.length === 0" 
              description="暂无快捷操作，点击右上角添加"
              :image-size="100"
            />
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="12">
        <el-card class="activity-card">
          <template #header>
            <span>最近活动</span>
          </template>
          <el-timeline>
            <el-timeline-item timestamp="2024-01-15 14:30" placement="top">
              <el-card>
                <h4>新订单创建</h4>
                <p>客户张三创建了新的销售订单 #SO20240115001</p>
              </el-card>
            </el-timeline-item>
            <el-timeline-item timestamp="2024-01-15 13:45" placement="top">
              <el-card>
                <h4>库存预警</h4>
                <p>商品"iPhone 15"库存不足，当前库存：5件</p>
              </el-card>
            </el-timeline-item>
            <el-timeline-item timestamp="2024-01-15 12:20" placement="top">
              <el-card>
                <h4>采购入库</h4>
                <p>采购订单 #PO20240115001 已完成入库</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加快捷方式对话框 -->
    <el-dialog
      v-model="addShortcutVisible"
      title="添加快捷方式"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="shortcutForm" :rules="shortcutRules" ref="shortcutFormRef" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="shortcutForm.name" placeholder="请输入快捷方式名称" />
        </el-form-item>
        
        <el-form-item label="路由路径" prop="path">
          <el-input v-model="shortcutForm.path" placeholder="例如：/sales/orders">
            <template #prepend>
              <el-icon><Link /></el-icon>
            </template>
          </el-input>
          <div class="form-tip">输入要跳转的路由路径，例如：/sales/orders</div>
        </el-form-item>
        
        <el-form-item label="图标" prop="icon">
          <el-select v-model="shortcutForm.icon" placeholder="请选择图标" filterable>
            <el-option
              v-for="icon in availableIcons"
              :key="icon.name"
              :label="icon.label"
              :value="icon.name"
            >
              <div style="display: flex; align-items: center;">
                <el-icon style="margin-right: 8px;"><component :is="icon.name" /></el-icon>
                {{ icon.label }}
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="按钮类型" prop="type">
          <el-radio-group v-model="shortcutForm.type">
            <el-radio value="primary">主要</el-radio>
            <el-radio value="success">成功</el-radio>
            <el-radio value="warning">警告</el-radio>
            <el-radio value="danger">危险</el-radio>
            <el-radio value="info">信息</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input 
            v-model="shortcutForm.description" 
            type="textarea"
            :rows="3"
            placeholder="可选：输入快捷方式的描述信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="addShortcutVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddShortcut">确定</el-button>
      </template>
    </el-dialog>

    <!-- 管理快捷方式对话框 -->
    <el-dialog
      v-model="manageShortcutsVisible"
      title="管理快捷方式"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-table :data="shortcuts" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        
        <el-table-column label="图标" width="80" align="center">
          <template #default="{ row }">
            <el-icon :size="20"><component :is="row.icon" /></el-icon>
          </template>
        </el-table-column>
        
        <el-table-column prop="name" label="名称" min-width="120" />
        
        <el-table-column prop="path" label="路径" min-width="150" />
        
        <el-table-column label="类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.type">{{ getTypeLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
        
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row, $index }">
            <el-button
              size="small"
              type="primary"
              link
              @click="handleEditShortcut(row, $index)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              link
              @click="handleDeleteShortcut($index)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-empty 
        v-if="shortcuts.length === 0" 
        description="暂无快捷操作"
        :image-size="150"
      />
      
      <template #footer>
        <el-button type="primary" @click="manageShortcutsVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 编辑快捷方式对话框 -->
    <el-dialog
      v-model="editShortcutVisible"
      title="编辑快捷方式"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="editForm" :rules="shortcutRules" ref="editFormRef" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入快捷方式名称" />
        </el-form-item>
        
        <el-form-item label="路由路径" prop="path">
          <el-input v-model="editForm.path" placeholder="例如：/sales/orders">
            <template #prepend>
              <el-icon><Link /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="图标" prop="icon">
          <el-select v-model="editForm.icon" placeholder="请选择图标" filterable>
            <el-option
              v-for="icon in availableIcons"
              :key="icon.name"
              :label="icon.label"
              :value="icon.name"
            >
              <div style="display: flex; align-items: center;">
                <el-icon style="margin-right: 8px;"><component :is="icon.name" /></el-icon>
                {{ icon.label }}
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="按钮类型" prop="type">
          <el-radio-group v-model="editForm.type">
            <el-radio value="primary">主要</el-radio>
            <el-radio value="success">成功</el-radio>
            <el-radio value="warning">警告</el-radio>
            <el-radio value="danger">危险</el-radio>
            <el-radio value="info">信息</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input 
            v-model="editForm.description" 
            type="textarea"
            :rows="3"
            placeholder="可选：输入快捷方式的描述信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editShortcutVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart, BarChart, SankeyChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getLast30DayLogin, getLoginTimeData } from '@/api/data'

// 注册必要的组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  BarChart,
  SankeyChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const router = useRouter()

// ========== 快捷操作相关 ==========
// 快捷操作列表
const shortcuts = ref([])

// 对话框显示控制
const addShortcutVisible = ref(false)
const manageShortcutsVisible = ref(false)
const editShortcutVisible = ref(false)

// 表单引用
const shortcutFormRef = ref(null)
const editFormRef = ref(null)

// 当前编辑的快捷方式索引
const editingIndex = ref(-1)

// 添加快捷方式表单
const shortcutForm = ref({
  name: '',
  path: '',
  icon: 'Star',
  type: 'primary',
  description: ''
})

// 编辑快捷方式表单
const editForm = ref({
  name: '',
  path: '',
  icon: 'Star',
  type: 'primary',
  description: ''
})

// 表单验证规则
const shortcutRules = {
  name: [
    { required: true, message: '请输入快捷方式名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入路由路径', trigger: 'blur' },
    { pattern: /^\//, message: '路径必须以 / 开头', trigger: 'blur' }
  ],
  icon: [
    { required: true, message: '请选择图标', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择按钮类型', trigger: 'change' }
  ]
}

// 可用图标列表
const availableIcons = [
  { name: 'Plus', label: '加号' },
  { name: 'Star', label: '星星' },
  { name: 'Document', label: '文档' },
  { name: 'ShoppingCart', label: '购物车' },
  { name: 'Box', label: '箱子' },
  { name: 'User', label: '用户' },
  { name: 'Setting', label: '设置' },
  { name: 'TrendCharts', label: '趋势图' },
  { name: 'DataLine', label: '数据线' },
  { name: 'Goods', label: '商品' },
  { name: 'Promotion', label: '推广' },
  { name: 'Sell', label: '销售' },
  { name: 'Folder', label: '文件夹' },
  { name: 'Files', label: '文件' },
  { name: 'Grid', label: '网格' },
  { name: 'List', label: '列表' },
  { name: 'Warning', label: '警告' },
  { name: 'Clock', label: '时钟' },
  { name: 'Calendar', label: '日历' },
  { name: 'Monitor', label: '监控' },
  { name: 'Phone', label: '电话' },
  { name: 'Message', label: '消息' },
  { name: 'ChatDotRound', label: '聊天' },
  { name: 'Tools', label: '工具' },
  { name: 'Operation', label: '操作' },
  { name: 'Management', label: '管理' },
  { name: 'Notification', label: '通知' },
  { name: 'Medal', label: '奖章' },
  { name: 'Trophy', label: '奖杯' },
  { name: 'Wallet', label: '钱包' },
  { name: 'PriceTag', label: '价格标签' },
  { name: 'Shop', label: '商店' },
  { name: 'OfficeBuilding', label: '办公楼' },
  { name: 'Van', label: '货车' },
  { name: 'Truck', label: '卡车' },
  { name: 'Ship', label: '船' }
]

// LocalStorage 键名
const SHORTCUTS_STORAGE_KEY = 'dashboard_shortcuts'

// 从 LocalStorage 加载快捷操作
const loadShortcuts = () => {
  try {
    const saved = localStorage.getItem(SHORTCUTS_STORAGE_KEY)
    if (saved) {
      shortcuts.value = JSON.parse(saved)
    } else {
      // 设置默认快捷操作
      shortcuts.value = [
        {
          id: Date.now() + 1,
          name: '新建销售订单',
          path: '/sales/orders',
          icon: 'Plus',
          type: 'primary',
          description: '创建新的销售订单'
        },
        {
          id: Date.now() + 2,
          name: '新建采购订单',
          path: '/purchase/orders',
          icon: 'ShoppingCart',
          type: 'success',
          description: '创建新的采购订单'
        },
        {
          id: Date.now() + 3,
          name: '商品管理',
          path: '/inventory/products',
          icon: 'Box',
          type: 'warning',
          description: '管理商品信息'
        },
        {
          id: Date.now() + 4,
          name: '用户管理',
          path: '/system/users',
          icon: 'User',
          type: 'info',
          description: '管理系统用户'
        }
      ]
      saveShortcuts()
    }
  } catch (error) {
    console.error('加载快捷操作失败:', error)
    shortcuts.value = []
  }
}

// 保存快捷操作到 LocalStorage
const saveShortcuts = () => {
  try {
    localStorage.setItem(SHORTCUTS_STORAGE_KEY, JSON.stringify(shortcuts.value))
  } catch (error) {
    console.error('保存快捷操作失败:', error)
    ElMessage.error('保存快捷操作失败')
  }
}

// 显示添加快捷方式对话框
const showAddShortcutDialog = () => {
  // 重置表单
  shortcutForm.value = {
    name: '',
    path: '',
    icon: 'Star',
    type: 'primary',
    description: ''
  }
  addShortcutVisible.value = true
  
  // 清除验证
  setTimeout(() => {
    shortcutFormRef.value?.clearValidate()
  }, 100)
}

// 显示管理快捷方式对话框
const showManageShortcutsDialog = () => {
  manageShortcutsVisible.value = true
}

// 处理快捷方式点击
const handleShortcutClick = (shortcut) => {
  if (shortcut.path) {
    router.push(shortcut.path)
  }
}

// 添加快捷方式
const handleAddShortcut = async () => {
  if (!shortcutFormRef.value) return
  
  await shortcutFormRef.value.validate((valid) => {
    if (valid) {
      const newShortcut = {
        id: Date.now(),
        ...shortcutForm.value
      }
      
      shortcuts.value.push(newShortcut)
      saveShortcuts()
      
      ElMessage.success('快捷方式添加成功')
      addShortcutVisible.value = false
    }
  })
}

// 编辑快捷方式
const handleEditShortcut = (row, index) => {
  editingIndex.value = index
  editForm.value = { ...row }
  editShortcutVisible.value = true
  
  // 清除验证
  setTimeout(() => {
    editFormRef.value?.clearValidate()
  }, 100)
}

// 保存编辑
const handleSaveEdit = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate((valid) => {
    if (valid) {
      shortcuts.value[editingIndex.value] = { ...editForm.value }
      saveShortcuts()
      
      ElMessage.success('快捷方式更新成功')
      editShortcutVisible.value = false
    }
  })
}

// 删除快捷方式
const handleDeleteShortcut = (index) => {
  ElMessageBox.confirm(
    '确定要删除这个快捷方式吗？',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    shortcuts.value.splice(index, 1)
    saveShortcuts()
    ElMessage.success('快捷方式删除成功')
  }).catch(() => {
    // 取消删除
  })
}

// 获取类型标签
const getTypeLabel = (type) => {
  const typeMap = {
    primary: '主要',
    success: '成功',
    warning: '警告',
    danger: '危险',
    info: '信息'
  }
  return typeMap[type] || type
}

const chartPeriod = ref('7d')
const loginDataLoading = ref(false)
const loginData = ref([])
const loginChartType = ref('bar') // 登录图表类型：bar, line, area, smooth
const loginTimeDataLoading = ref(false)
const loginTimeData = ref([]) // 登录时间段数据

// ========== 业务统计数据 ==========
// 采购统计
const purchaseStats = ref({
  count: 0,
  amount: '0'
})

// 配货统计
const distributionStats = ref({
  count: 0,
  pending: 0
})

// 批发统计
const wholesaleStats = ref({
  count: 0,
  amount: '0'
})

// 移仓统计
const transferStats = ref({
  count: 0,
  items: 0
})

// 数据流统计
const dataFlowStats = ref({
  total: 0,
  growth: 0
})

// 集成统计
const integrationStats = ref({
  apis: 0,
  successRate: 0
})

// 获取业务统计数据
const fetchBusinessStats = () => {
  // 采购统计 - 模拟数据
  purchaseStats.value = {
    count: 68,
    amount: '456,789'
  }
  
  // 配货统计 - 模拟数据
  distributionStats.value = {
    count: 145,
    pending: 23
  }
  
  // 批发统计 - 模拟数据
  wholesaleStats.value = {
    count: 89,
    amount: '678,900'
  }
  
  // 移仓统计 - 模拟数据
  transferStats.value = {
    count: 34,
    items: 1256
  }
  
  // 数据流统计 - 模拟数据
  dataFlowStats.value = {
    total: 15678,
    growth: 23.5
  }
  
  // 集成统计 - 模拟数据
  integrationStats.value = {
    apis: 3456,
    successRate: 99.8
  }
}

// 刷新业务统计数据
const refreshBusinessStats = () => {
  fetchBusinessStats()
  ElMessage.success('业务统计数据已刷新')
}

// ========== 业务数据流转桑基图 ==========
// 业务数据流转桑基图配置
const dataFlowSankeyOption = computed(() => {
  return {
    title: {
      text: '业务数据流转全景图',
      subtext: '展示从进货到最终跳转的完整业务流程',
      left: 'center',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold'
      },
      subtextStyle: {
        fontSize: 12,
        color: '#999'
      }
    },
    tooltip: {
      trigger: 'item',
      triggerOn: 'mousemove',
      formatter: function(params) {
        if (params.dataType === 'edge') {
          return `${params.data.source} → ${params.data.target}<br/>数量: ${params.data.value} 单`
        } else {
          return `${params.name}<br/>总量: ${params.value} 单`
        }
      }
    },
    series: [
      {
        type: 'sankey',
        layout: 'none',
        emphasis: {
          focus: 'adjacency'
        },
        nodeAlign: 'justify',
        layoutIterations: 32,
        nodeGap: 30,
        nodeWidth: 20,
        left: '5%',
        right: '15%',
        top: '15%',
        bottom: '10%',
        data: [
          // 第一层：进货
          { name: '进货', itemStyle: { color: '#5470C6' } },
          // 第二层：分销
          { name: '分销', itemStyle: { color: '#91CC75' } },
          // 第三层：零售、批发
          { name: '零售', itemStyle: { color: '#FAC858' } },
          { name: '批发', itemStyle: { color: '#EE6666' } },
          // 第四层：配货
          { name: '配货', itemStyle: { color: '#73C0DE' } },
          // 第五层：调拨
          { name: '调拨', itemStyle: { color: '#3BA272' } },
          // 第六层：跳转
          { name: '跳转', itemStyle: { color: '#FC8452' } }
        ],
        links: [
          // 进货 -> 分销
          { source: '进货', target: '分销', value: 1000 },
          
          // 分销 -> 零售、批发
          { source: '分销', target: '零售', value: 600 },
          { source: '分销', target: '批发', value: 400 },
          
          // 零售 -> 配货
          { source: '零售', target: '配货', value: 580 },
          
          // 批发 -> 配货
          { source: '批发', target: '配货', value: 380 },
          
          // 配货 -> 调拨
          { source: '配货', target: '调拨', value: 900 },
          
          // 调拨 -> 跳转
          { source: '调拨', target: '跳转', value: 850 }
        ],
        lineStyle: {
          color: 'gradient',
          curveness: 0.5,
          opacity: 0.3
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{b}: {c}单',
          fontSize: 13,
          fontWeight: 'bold'
        }
      }
    ]
  }
})

// 刷新数据流转图
const refreshDataFlow = () => {
  ElMessage.success('数据流转图已刷新')
}

// 业务数据对比图表配置
const businessCompareChartOption = computed(() => {
  return {
    title: {
      text: '各业务模块数据对比',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        let result = params[0].name + '<br/>'
        params.forEach(item => {
          result += item.marker + ' ' + item.seriesName + ': ' + item.value + '<br/>'
        })
        return result
      }
    },
    legend: {
      data: ['订单数/任务数', '金额/件数'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['采购', '配货', '批发', '移仓'],
      axisLabel: {
        rotate: 0
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '订单数/任务数',
        type: 'bar',
        data: [
          purchaseStats.value.count,
          distributionStats.value.count,
          wholesaleStats.value.count,
          transferStats.value.count
        ],
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#667eea' },
              { offset: 1, color: '#764ba2' }
            ]
          }
        }
      },
      {
        name: '金额/件数',
        type: 'bar',
        data: [
          parseInt(String(purchaseStats.value.amount).replace(/,/g, '')) / 1000,
          distributionStats.value.pending,
          parseInt(String(wholesaleStats.value.amount).replace(/,/g, '')) / 1000,
          transferStats.value.items
        ],
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#f093fb' },
              { offset: 1, color: '#f5576c' }
            ]
          }
        }
      }
    ]
  }
})

// 业务数据分布图表配置
const businessDistributionChartOption = computed(() => {
  const data = [
    { 
      value: purchaseStats.value.count, 
      name: '采购订单',
      itemStyle: { color: '#667eea' }
    },
    { 
      value: distributionStats.value.count, 
      name: '配货任务',
      itemStyle: { color: '#f093fb' }
    },
    { 
      value: wholesaleStats.value.count, 
      name: '批发订单',
      itemStyle: { color: '#4facfe' }
    },
    { 
      value: transferStats.value.count, 
      name: '移仓单据',
      itemStyle: { color: '#43e97b' }
    }
  ]
  
  return {
    title: {
      text: '业务数据分布占比',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}<br/>数量: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle',
      formatter: (name) => {
        const item = data.find(d => d.name === name)
        return item ? `${name} (${item.value})` : name
      }
    },
    series: [
      {
        name: '业务分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold',
            formatter: '{b}\n{c}个'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }
})

// 销售趋势图表配置
const salesChartOption = computed(() => {
  const dates = []
  const salesData = []
  
  // 根据选择的时间段生成数据
  const days = chartPeriod.value === '7d' ? 7 : chartPeriod.value === '30d' ? 30 : 90
  
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    dates.push(date.toLocaleDateString())
    salesData.push(Math.floor(Math.random() * 50000) + 10000)
  }
  
  return {
    title: {
      text: '销售趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>销售额: ¥{c}'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '销售额',
        type: 'line',
        smooth: true,
        data: salesData,
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        }
      }
    ]
  }
})

// 登录时间段统计图表配置
const loginTimeChartOption = computed(() => {
  // 时间段颜色映射
  const timeColors = {
    '早晨': '#F56C6C',   // 红色 6:00-9:00
    '上午': '#E6A23C',   // 橙色 9:00-12:00
    '中午': '#FFBA00',   // 黄色 12:00-14:00
    '下午': '#67C23A',   // 绿色 14:00-18:00
    '晚上': '#409EFF',   // 蓝色 18:00-22:00
    '凌晨': '#909399'    // 灰色 22:00-6:00
  }
  
  // 转换数据格式
  const chartData = loginTimeData.value.map(item => ({
    value: item.登录次数,
    name: item.时间段,
    itemStyle: { 
      color: timeColors[item.时间段] || '#409EFF'
    }
  }))
  
  return {
    title: {
      text: '登录时间段分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}<br/>登录次数: {c}次 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle',
      formatter: (name) => {
        const item = loginTimeData.value.find(d => d.时间段 === name)
        return item ? `${name} (${item.登录次数})` : name
      }
    },
    series: [
      {
        name: '登录时间段',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold',
            formatter: '{b}\n{c}次'
          }
        },
        labelLine: {
          show: false
        },
        data: chartData
      }
    ]
  }
})

// 登录次数图表配置
const loginChartOption = computed(() => {
  // 反转数组，让日期从旧到新排列（从左到右）
  const reversedData = [...loginData.value].reverse()
  const dates = reversedData.map(item => item.dayKey)
  const counts = reversedData.map(item => item.num)
  
  // 根据图表类型生成不同的配置
  const getSeriesConfig = () => {
    const baseConfig = {
      name: '登录次数',
      data: counts
    }
    
    switch (loginChartType.value) {
      case 'bar':
        // 柱状图
        return {
          ...baseConfig,
          type: 'bar',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: '#67C23A' },
                { offset: 1, color: '#85CE61' }
              ]
            },
            borderRadius: [4, 4, 0, 0]
          },
          emphasis: {
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: '#85CE61' },
                  { offset: 1, color: '#67C23A' }
                ]
              }
            }
          }
        }
      
      case 'line':
        // 折线图
        return {
          ...baseConfig,
          type: 'line',
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#409EFF'
          },
          lineStyle: {
            width: 3,
            color: '#409EFF'
          },
          emphasis: {
            itemStyle: {
              color: '#66B1FF',
              borderColor: '#409EFF',
              borderWidth: 2
            }
          }
        }
      
      case 'area':
        // 面积图
        return {
          ...baseConfig,
          type: 'line',
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#E6A23C'
          },
          lineStyle: {
            width: 2,
            color: '#E6A23C'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(230, 162, 60, 0.5)' },
                { offset: 1, color: 'rgba(230, 162, 60, 0.1)' }
              ]
            }
          }
        }
      
      case 'smooth':
        // 平滑曲线
        return {
          ...baseConfig,
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#F56C6C'
          },
          lineStyle: {
            width: 3,
            color: '#F56C6C'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(245, 108, 108, 0.3)' },
                { offset: 1, color: 'rgba(245, 108, 108, 0.05)' }
              ]
            }
          }
        }
      
      default:
        return baseConfig
    }
  }
  
  // 图表类型名称
  const chartTypeNames = {
    bar: '柱状图',
    line: '折线图',
    area: '面积图',
    smooth: '平滑曲线'
  }
  
  return {
    title: {
      text: `最近30天登录次数（${chartTypeNames[loginChartType.value]}）`,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>登录次数: {c}次',
      axisPointer: {
        type: loginChartType.value === 'bar' ? 'shadow' : 'line'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: loginChartType.value === 'bar',
      data: dates,
      axisLabel: {
        rotate: 45,
        formatter: (value) => {
          // 只显示月-日
          const date = new Date(value)
          return `${date.getMonth() + 1}-${date.getDate()}`
        }
      }
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [getSeriesConfig()]
  }
})

// 获取登录数据
const fetchLoginData = async () => {
  try {
    loginDataLoading.value = true
    const response = await getLast30DayLogin()
    
    if (response.code === 200) {
      // 数据已经按日期排序，直接使用
      loginData.value = response.data || []
    } else {
      ElMessage.error(response.msg || '获取登录数据失败')
    }
  } catch (error) {
    console.error('获取登录数据失败:', error)
    ElMessage.error(error.message || '获取登录数据失败')
  } finally {
    loginDataLoading.value = false
  }
}

// 刷新登录数据
const refreshLoginData = () => {
  fetchLoginData()
}

// 获取登录时间段数据
const fetchLoginTimeData = async () => {
  try {
    loginTimeDataLoading.value = true
    const response = await getLoginTimeData()
    
    if (response.code === 200) {
      loginTimeData.value = response.data || []
    } else {
      ElMessage.error(response.msg || '获取登录时间段数据失败')
    }
  } catch (error) {
    console.error('获取登录时间段数据失败:', error)
    ElMessage.error(error.message || '获取登录时间段数据失败')
  } finally {
    loginTimeDataLoading.value = false
  }
}

// 刷新登录时间段数据
const refreshLoginTimeData = () => {
  fetchLoginTimeData()
}

// 生命周期
onMounted(() => {
  // 加载快捷操作
  loadShortcuts()
  // 页面加载时获取登录数据
  fetchLoginData()
  // 获取登录时间段数据
  fetchLoginTimeData()
  // 获取业务统计数据
  fetchBusinessStats()
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: white;
}

.stat-icon.sales {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.orders {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.inventory {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.customers {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-icon.purchase {
  background: linear-gradient(135deg, #FA8BFF 0%, #2BD2FF 90%, #2BFF88 100%);
}

.stat-icon.distribution {
  background: linear-gradient(135deg, #FEC163 0%, #DE4313 100%);
}

.stat-icon.wholesale {
  background: linear-gradient(135deg, #A8EDEA 0%, #FED6E3 100%);
}

.stat-icon.transfer {
  background: linear-gradient(135deg, #FF9A8B 0%, #FF6A88 55%, #FF99AC 100%);
}

.stat-icon.dataflow {
  background: linear-gradient(135deg, #8EC5FC 0%, #E0C3FC 100%);
}

.stat-icon.integration {
  background: linear-gradient(135deg, #FBC2EB 0%, #A6C1EE 100%);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-sub {
  font-size: 12px;
  color: #C0C4CC;
  margin-top: 2px;
}

.charts-row {
  margin-bottom: 20px;
}

.login-stats-row {
  margin-bottom: 20px;
}

.chart-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-actions .el-radio-group {
  margin-right: 8px;
}

.header-actions :deep(.el-radio-button__inner) {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 15px;
}

.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  text-align: center;
  color: #909399;
}

.chart-placeholder p {
  margin: 10px 0 5px 0;
  font-size: 16px;
}

.chart-placeholder small {
  font-size: 12px;
}

.bottom-row {
  margin-bottom: 20px;
}

.action-card,
.activity-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.quick-actions .el-button {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.el-timeline {
  padding-left: 0;
}

.el-timeline-item .el-card {
  margin: 0;
  border: none;
  box-shadow: none;
}

.el-timeline-item .el-card h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
}

.el-timeline-item .el-card p {
  margin: 0;
  font-size: 13px;
  color: #606266;
}

/* 表单提示 */
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.5;
}

/* 快捷操作按钮容器优化 */
.quick-actions {
  min-height: 120px;
}

.quick-actions .el-empty {
  padding: 20px 0;
}

/* 管理对话框中的空状态 */
.el-dialog__body .el-empty {
  padding: 40px 0;
}

/* 图标选择器选项样式优化 */
:deep(.el-select-dropdown__item) {
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
}
</style>
